package config

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"go-chain-api/global"
	"go-chain-api/tools"
	"log"
	"os"
	"path/filepath"
	"time"
)

type Config struct {
	vp *viper.Viper
}

func NewConfig() (*Config, error) {
	// 获取可执行文件的绝对路径
	exec, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	// 基于可执行文件的路径构建配置文件的绝对路径
	configPath := filepath.Join(exec, "config", "config.yaml")
	viper.SetConfigFile(configPath)
	vp := viper.New()
	vp.SetConfigName("config")
	vp.AddConfigPath("config")
	vp.SetConfigType("yaml")
	err = vp.ReadInConfig()
	if err != nil {
		return nil, err
	}
	return &Config{vp}, nil
}

func (config *Config) ReadSection(k string, v interface{}) error {
	err := config.vp.UnmarshalKey(k, v)
	if err != nil {
		return err
	}
	return nil
}

func SetupConfig() {
	conf, err := NewConfig()
	if err != nil {
		log.Panic("NewConfig error : ", err)
	}
	err = conf.ReadSection("Database", &global.DbConfig)
	if err != nil {
		log.Panic("ReadSection - Database error : ", err)
	}
	err = conf.ReadSection("BlockChain", &global.BlockChainConfig)
	if err != nil {
		log.Panic("ReadSection - BlockChain error : ", err)
	}
	err = conf.ReadSection("Email", &global.EmailConfig)
	if err != nil {
		log.Panic("ReadSection - Email error : ", err)
	}
	err = conf.ReadSection("CallbackUrl", &global.CallBackUrlConfig)
	if err != nil {
		log.Panic("ReadSection - CallbackUrl error : ", err)
	}
	err = conf.ReadSection("Redis", &global.RedisConfig)
	if err != nil {
		log.Panic("ReadSection - RedisConfig error : ", err)
	}
	//err = conf.ReadSection("MysqlDatabase", &global.MysqlDbConfig)
	//if err != nil {
	//	log.Panic("ReadSection - MysqlDbConfig error : ", err)
	//}
}

func SetupDBEngine() {
	var err error
	global.MysqlDbEngine, err = NewDBEngine(global.MysqlDbConfig)
	if err != nil {
		log.Panic("NewDBEngine error : ", err)
	}
}

func SetupMongoDBEngine() {
	var err error
	global.DBEngine, err = NewMongodbEngine(global.DbConfig)
	if err != nil {
		log.Panic("NewDBEngine error : ", err)
	}
}

func InitRedis() {
	global.RedisEngine = redis.NewClient(&redis.Options{
		Addr:     global.RedisConfig.Addr,     // redis地址
		Password: global.RedisConfig.Password, // redis密码，没有则留空
		DB:       global.RedisConfig.Index,    // 默认数据库为0
	})
	global.RedisEngine.Set(context.TODO(), "test1", "test1", 5*time.Minute)
	a := global.RedisEngine.Get(context.TODO(), "test1")
	fmt.Println("a", a)
}

func InitConnectionPool(size int) {
	global.ConnPool = tools.NewConnectionPool(size)
}
